package net.home.test.action;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.web.belerofont.action.URIMap;
import net.web.belerofont.action.support.ActionSupport;
import net.web.belerofont.annotation.Inject;
import net.web.belerofont.annotation.Interceptor;
import net.web.belerofont.annotation.Logic;
import net.web.belerofont.annotation.WebMethod;


@Logic(
		path="/belerofonte/SendFile.do",
		forwards= {
		},
		interceptors={
			@Interceptor(className="net.home.test.interceptors.SendFileInterceptor")
		}
	)
public class SendFileAction extends ActionSupport {
	
	private ThreadLocal<ServletContext> context = new ThreadLocal<ServletContext>();
	private ThreadLocal<HttpServletRequest> request = new ThreadLocal<HttpServletRequest>();
	private ThreadLocal<HttpServletResponse> response = new ThreadLocal<HttpServletResponse>();
	
	@Inject (direction="IN")
	public void setContext(ServletContext context){
		this.context.set(context);
	}
	
	@Inject (direction="IN")
	public void setRequest(HttpServletRequest request){
		this.request.set(request);
	}
	
	@Inject (direction="IN")
	public void setResponse(HttpServletResponse response){
		this.response.set(response);
	}

	@WebMethod
	public URIMap image() {

		try {
			HttpSession session = request.get().getSession();
			
			response.get().setContentType("image/jpg");
			response.get().addHeader("pragma","no-cache");
			response.get().addIntHeader("cache-control",0);
			ServletOutputStream os;

			os = response.get().getOutputStream();
			String fileName = context.get().getRealPath("/img/Miguel6.jpg");
			
			session.setAttribute("fileName", fileName);
			
			System.out.println("Resource: " + fileName);
			
			InputStream is = context.get().getResourceAsStream("/img/Miguel6.jpg");
			
			int read = 0;
			byte[] bytes = new byte[2048]; 
			while((read = is.read(bytes)) != -1) {
				os.write(bytes,0,read);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}
}
